//
//  PopNumberViewController.m
//  wuliangye
//
//  Created by jarze on 16/2/17.
//  Copyright © 2016年 jarze. All rights reserved.
//

#import "PopNumberViewController.h"
#import "GCD/GCD.h"
#import "POPNumberAnimation.h"
#import "UIView+SetRect.h"
@interface PopNumberViewController ()<POPNumberAnimationDelegate>
@property (nonatomic, strong) POPNumberAnimation *numberAnimation;
@property (nonatomic, strong) UILabel            *label;
@property (nonatomic, strong) GCDTimer           *timer;
@property (nonatomic, strong) UIView         *pointView;
@property (nonatomic, strong) CAShapeLayer   *shapeLayer;
@property (nonatomic, strong) CADisplayLink  *displayLink;

@property (nonatomic, strong)  UIView   *upView;
@property (nonatomic, strong)  UILabel  *upLabel;
@property (nonatomic, strong)  UIView   *downView;
@property (nonatomic, strong)  UILabel  *downLabel;
@property (nonatomic, strong) GCDTimer           *timer1;

@end

@implementation PopNumberViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // Do any additional setup after loading the view.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self setup];
    [self setUp1];
    [self setUp3];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setup {
    
    _label               = [[UILabel alloc] initWithFrame:CGRectMake(50, 80, 250, 100)];
    _label.textAlignment = NSTextAlignmentCenter;
//    _label.center        = self.view.center;
    [self.view addSubview:_label];
    // Init numberAnimation.
    self.numberAnimation          = [[POPNumberAnimation alloc] init];
    self.numberAnimation.delegate = self;
    // Timer event.
    __weak PopNumberViewController *weakSelf = self;
    self.timer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    [self.timer event:^{
        // Start animation.
        [weakSelf configNumberAnimation];
        [weakSelf.numberAnimation startAnimation];
        
    } timeIntervalWithSecs:4.f];
    [self.timer start];
}

- (void)setUp3
{
    /*
     给upView的frame值做动画才是label能够混色显示的核心
     
     upView(红色背景)   ===>  upLabel(白色底字)
     |                       |
     |                       |
     |                       |
     |                       |
     downView(白色背景) ===> downLabel(红色底字)
     
     */
    
    // 上面一层
    {
        // 红色背景
        _upView                     = [[UIView alloc] initWithFrame:CGRectMake(50, 200, 220, 17)];
//        _upView.center              = self.view.center;
        _upView.layer.cornerRadius  = 5.f;
        _upView.backgroundColor     = [UIColor redColor];
        _upView.layer.masksToBounds = YES; // 核心(不让subview显示超出范围)
        [self.view addSubview:_upView];
        
        // 白色底字
        _upLabel                    = [[UILabel alloc] initWithFrame:_upView.bounds];
        _upLabel.font               = [UIFont systemFontOfSize:12];
        _upLabel.text               = @"YouXianMing - iOS Programmer";
        _upLabel.textColor          = [UIColor whiteColor];
        _upLabel.textAlignment      = NSTextAlignmentCenter;
        [_upView addSubview:_upLabel];
    }
    
    // 下面一层
    {
        // 白色背景
        _downView                     = [[UIView alloc] initWithFrame:CGRectMake(50, 200, 220, 17)];
//        _downView.center              = self.view.center;
        _downView.layer.cornerRadius  = 5.f;
        _downView.backgroundColor     = [UIColor whiteColor];
        [self.view addSubview:_downView];
        
        // 红色底字
        _downLabel                    = [[UILabel alloc] initWithFrame:_downView.bounds];
        _downLabel.textColor          = [UIColor redColor];
        _downLabel.font               = [UIFont systemFontOfSize:12];
        _downLabel.text               = @"YouXianMing - iOS Programmer";
        _downLabel.textAlignment = NSTextAlignmentCenter;
        [_downView addSubview:_downLabel];
    }
    
    // 显示上面一层
    [self.view bringSubviewToFront:_upView];
    
    // 给上面一层的frame值做动画
    _timer1 = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    [_timer1 event:^{
        
        [UIView animateWithDuration:0.5f delay:0.f usingSpringWithDamping:3.f initialSpringVelocity:0 options:0 animations:^{
            
            _upView.width = arc4random() % 220;
            
        } completion:nil];
        
    } timeInterval:NSEC_PER_SEC];
    [_timer1 start];
}
- (void)setUp1
{

    self.shapeLayer           = [CAShapeLayer layer];
    self.shapeLayer.frame     = self.view.bounds;
    self.shapeLayer.fillColor = [UIColor redColor].CGColor;
    self.shapeLayer.path      = [self calculatePathWithPoint:CGPointMake(Width / 2.f, Height / 2.f)].CGPath;
    [self.view.layer addSublayer:self.shapeLayer];
    
    self.pointView        = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 4, 4)];
    self.pointView.center = self.view.center;
    [self.view addSubview:self.pointView];
    
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkEvent)];
    [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureEvent:)];
    [self.view addGestureRecognizer:panGesture];

    
}

- (UIBezierPath *)calculatePathWithPoint:(CGPoint)point {
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, Height / 2.f)];
    [path addLineToPoint:CGPointMake(0, Height)];
    [path addLineToPoint:CGPointMake(Width, Height)];
    [path addLineToPoint:CGPointMake(Width, Height / 2.f)];
    [path addQuadCurveToPoint:CGPointMake(0, Height / 2.f)
                 controlPoint:point];
    
    return path;
}

- (void)panGestureEvent:(UIPanGestureRecognizer *)panGesture {
    
    CGPoint point          = [panGesture locationInView:panGesture.view];
    CGPoint calculatePoint = CGPointMake((point.x + self.view.center.x) / 2.f, (point.y + self.view.center.y) / 2.f);
    
    if (panGesture.state == UIGestureRecognizerStateChanged) {
        
        self.shapeLayer.path  = [self calculatePathWithPoint:calculatePoint].CGPath;
        self.pointView.center = calculatePoint;
        
    } else if (panGesture.state == UIGestureRecognizerStateCancelled ||
               panGesture.state == UIGestureRecognizerStateEnded ||
               panGesture.state == UIGestureRecognizerStateFailed) {
        
        [UIView animateWithDuration:1.0 delay:0.0 usingSpringWithDamping:0.25f initialSpringVelocity:0
                            options:UIViewAnimationOptionCurveEaseInOut
                         animations:^{
                             
                             self.pointView.center = self.view.center;
                             
                         } completion:nil];
    }
}

- (void)displayLinkEvent {
    
    CALayer *layer       = self.pointView.layer.presentationLayer;
    self.shapeLayer.path = [self calculatePathWithPoint:layer.position].CGPath;
    
    
}


- (void)configNumberAnimation {
    
    self.numberAnimation.fromValue      = self.numberAnimation.currentValue;
    self.numberAnimation.toValue        = (arc4random() % 101 / 1.f);
    self.numberAnimation.duration       = 2.f;
    self.numberAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.69 :0.11 :0.32 :0.88];
    [self.numberAnimation saveValues];
}

- (void)POPNumberAnimation:(POPNumberAnimation *)numberAnimation currentValue:(CGFloat)currentValue {
    // Init string.
    NSString *numberString = [NSString stringWithFormat:@"%.1f", currentValue];
    NSString *mpsString    = @"mps";
    NSString *totalString  = [NSString stringWithFormat:@"%@ %@", numberString, mpsString];
    
//    // Init string ranges.
    NSRange   mpsRange     = [totalString rangeOfString:mpsString];
    NSRange   numberRange  = [totalString rangeOfString:numberString];
//    NSRange   totalRange   = NSMakeRange(0, totalString.length);
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:totalString];
    
    [str addAttribute:NSForegroundColorAttributeName value:[self numColorWithValue:currentValue / 100.f] range:mpsRange];
    [str addAttribute:NSForegroundColorAttributeName value:[self mpsColorWithValue:currentValue / 100.f] range:numberRange];
   
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:mpsRange];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:numberRange];

    _label.attributedText = str;

}
- (UIColor *)numColorWithValue:(CGFloat)value {
    
    return [UIColor colorWithRed:value green:0 blue:0 alpha:1.f];
}

- (UIColor *)mpsColorWithValue:(CGFloat)value {
    
    return [UIColor colorWithRed:value green:value / 2.f blue:value / 3.f alpha:1.f];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.timer destroy];
    self.timer = nil;
    
    [self.timer1 destroy];
    self.timer1 = nil;
    
    [self.displayLink invalidate];
    self.displayLink = nil;
    
}
@end
